package fr.xebia.monitoring.beans.formater;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import fr.xebia.monitoring.beans.AggregatedMeasure;
import fr.xebia.monitoring.beans.AggregatedMeasures;
import fr.xebia.monitoring.beans.Measure;

public class MeasureXmlFormater implements MeasureFormater {

	private static final String DEFAULT_ENCODING = "UTF-8";
	private JAXBContext context;

	public static String getDefaultEncoding() {
		return DEFAULT_ENCODING;
	}

	public MeasureXmlFormater() {
		super();
		try {
			context = JAXBContext.newInstance("fr.xebia.monitoring.beans");
		} catch (JAXBException e) {
			throw new RuntimeException("Can't create JAXB Context", e);
		}
	}

	public String format(AggregatedMeasures agregatedMeasures) throws FormaterException {
		StringWriter stringWriter = new StringWriter();
		format(agregatedMeasures, stringWriter);
		return stringWriter.toString();
	}

	public void format(AggregatedMeasures agregatedMeasures, Writer writer) throws FormaterException {
		try {
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty("jaxb.encoding", DEFAULT_ENCODING);
			marshaller.marshal(agregatedMeasures, writer);
			writer.write('\n');
		} catch (JAXBException e) {
			throw new FormaterException("Can't convert data to XML", e);
		} catch (IOException e) {
			throw new FormaterException("Can't write to Writer", e);
		}
	}

	public String format(AggregatedMeasure agregatedMeasure) throws FormaterException {
		try {
			StringWriter writer = new StringWriter();
			Marshaller marshaller = context.createMarshaller();
			marshaller.marshal(agregatedMeasure, writer);
			return writer.toString();
		} catch (JAXBException e) {
			throw new FormaterException("Can't convert data to XML", e);
		}
	}

	public void format(Measure[] measures, Writer writer) throws FormaterException {
		try {
			Marshaller marshaller = context.createMarshaller();
			for (Measure measure : measures) {
				marshaller.marshal(measure, writer);	
			}
		} catch (JAXBException e) {
			throw new FormaterException("Can't convert data to XML", e);
		}
	}

	public String format(Measure[] measures) throws FormaterException {
		StringWriter writer = new StringWriter();
		format(measures, writer);
		return writer.toString();
	}

	public String format(Measure measure) throws FormaterException {
		try {
			StringWriter writer = new StringWriter();
			Marshaller marshaller = context.createMarshaller();
			marshaller.marshal(measure, writer);
			return writer.toString();
		} catch (JAXBException e) {
			throw new FormaterException("Can't convert data to XML", e);
		}
	}
}
